package com.longer.demo.biz.service;

import com.longer.demo.biz.domain.SequenceDO;
import com.longer.demo.biz.repository.SequenceDOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

/**
 * @program: mybatis
 * @description:
 * @author: SunBiaoLong
 * @create: 2019-01-15 09:05
 **/
@Service
public class SequenceServiceImpl implements SequenceService {
	@Autowired(required = false)
	private SequenceDOMapper sequenceDOMapper;

	/**
	 * 目前未考虑sequence;最大值的问题
	 * 生成OrderNo,如果创建订单的时候出现了异常,生成的订单号不应该回滚
	 *     这样保证了订单编号的唯一性
	 * @return
	 */
	@Transactional(propagation= Propagation.REQUIRES_NEW)
	@Override
	public String generateSequence(String name) {
		//订单号为16位
		StringBuilder stringBuilder = new StringBuilder();
		//前八位为年月日
		String dateString = LocalDate.now().toString().replace("-", "");
		stringBuilder.append(dateString);

		//中间六位为自增序列
		SequenceDO sequenceDO = sequenceDOMapper.getSequenceByName(name);
		int sequence = sequenceDO.getCurrentValue();
//		@TODO 需要设置最大值.如果超过最大值,那么应该重新开始循环
		sequenceDO.setCurrentValue(sequence+sequenceDO.getStep());
		sequenceDOMapper.updateByPrimaryKey(sequenceDO);
		String sequenceStr = String.valueOf(sequence);
		for (int i = 0; i < 6-sequenceStr.length(); i++) {
			stringBuilder.append(0);
		}
		stringBuilder.append(sequenceStr);

		//最后两位为 分库分表位--制定某用户的指定订单保存的表
		//这里不做演示
//		Integer userId = 100023;
//		int tableIndex = userId % 100;
		//暂时写死
		stringBuilder.append("00");

		return stringBuilder.toString();
	}

}
